package algorithm.leetcode;

import java.util.Arrays;

public class LeetCode_56_merge {

    public int[][] merge(int[][] intervals) {
        Arrays.sort(intervals, (o1, o2) -> o1[0] - o2[0]);
        int[][] res = new int[intervals.length][2];
        int index = 0;

        for (int i = 0; i < intervals.length; i++) {
            if (index == 0 || intervals[i][0] > res[index - 1][1]) {
                res[index] = intervals[i];
                index += 1;
            } else {
                res[index - 1][1] = Math.max(res[index - 1][1], intervals[i][1]);
            }
        }
        return Arrays.copyOf(res, index);
    }

    public static void main(String[] args) {
        LeetCode_56_merge leetCode_56_merge = new LeetCode_56_merge();
        //[[1,3],[2,6],[8,10],[15,18]]
        int[][] intervals = {{1, 3}, {2, 6}, {8, 10}, {15, 18}};
        int[][] merge = leetCode_56_merge.merge(intervals);
        for (int[] item : merge) {
            System.out.println(item[0] + "," + item[1]);
        }
    }
}
